﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KP_CommonLibrary.KP_CommonControls;

namespace KP_CommonLibrary.KP_CoreUI
{
    public partial class KP_EditVoucherItem : KP_CommonLibrary.KP_CommonControls.KP_FormSaveItem,IContainerDataSource
    {
        KP_Business.KP_BLVoucherBase Business { get; set; }

        public KP_EditVoucherItem()
        {
            InitializeComponent();

        }
        protected CurrencyManager ParentBinding { get; set; }
        protected DataRow CurrentRow
        {
            get
            {
                if (MasterBindingSource.DataSource != null)
                {
                    return (MasterBindingSource.DataSource as DataRowView).Row;
                }
                return null;
            }
        }

        public event EventHandler FormStateChanged;
        public event FormStateChangingHandler FormStateChanging;
        private FormState fFormState = FormState.Unspecified;

        public FormState FormState
        {
            get { return fFormState; }
            set
            {
                if (fFormState != value)
                {
                    FormStateChangingArgs e = new FormStateChangingArgs(fFormState, value);
                    if (FormStateChanging != null)
                        FormStateChanging(this, e);
                    if (!e.Cancel)
                    {
                        fFormState = value;
                        if (FormStateChanged != null)
                            FormStateChanged(this, new EventArgs());
                        //kTestBindingController1.ContainerChangeState(value);
                    }
                }
            }

        }
        protected virtual DataRow[] ChildRows
        {
            get
            {

                if (FormState.Insert != FormState)
                {
                    List<DataRow> lstRow = new List<DataRow>();
                    //Add Current Row
                    lstRow.AddRange(CurrentRow.GetChildRows(Business.RelationName));
                    //Add Original Row
                    DataRow[] originalRows = CurrentRow.GetChildRows(Business.RelationName, DataRowVersion.Original);
                    for (int i = 0; i < originalRows.Length; i++)
                    {
                        if (lstRow.Contains(originalRows[i]))
                            continue;

                        lstRow.Add(originalRows[i]);
                    }
                    return lstRow.ToArray();
                }
                return CurrentRow.GetChildRows(Business.RelationName);
            }
        }
        protected virtual void SetDataSource(object obj)
        {
            bool performBinding = false;
            if (MasterBindingSource.DataSource == null)
                performBinding = true;
            MasterBindingSource.DataSource = obj;
            DetailBindingSource.DataMember = Business.RelationName;
            if (performBinding)
                kP_BindingController.BindingControl();
            CustomReadData(CurrentRow, CurrentRow.GetChildRows(Business.RelationName));
        }

        public virtual void CustomReadData(DataRow masterRow, DataRow[] detailRows)
        {

        }

        protected virtual void EndEdit()
        {
            try
            {
                DetailBindingSource.EndEdit();
                MasterBindingSource.EndEdit();
            }
            catch (Exception ex)
            {
                DetailBindingSource.CurrencyManager.EndCurrentEdit();
                ParentBinding.EndCurrentEdit();

            }
        }

        public virtual void CustomWriteData(DataRow CurrentRow, DataTable tblDetail)
        {
            //throw new NotImplementedException();

        }
        public virtual void CustomWriteData(DataRow CurrentRow, DataRow[] detailRows)
        {
            //throw new NotImplementedException();

        }
        public virtual void AddNew(CurrencyManager parentBinding)
        {
            try
            {
                ParentBinding = parentBinding;
                LoadDependencyData();
                ParentBinding.AddNew();
                InitMasterData((ParentBinding.Current as DataRowView).Row);
                SetDataSource(ParentBinding.Current);
                FormState = FormState.Insert;
            }
            catch (Exception ex)
            {
                try
                {
                    ParentBinding.CancelCurrentEdit();
                }
                catch
                {
                }
                throw ex;
            }
        }
        public virtual void Edit(CurrencyManager parentBinding)
        {
            ParentBinding = parentBinding;
            LoadDependencyData();
            SetDataSource(parentBinding.Current);
            FormState = FormState.Update;
        }
        protected void InitMasterData(DataRow masterRow)
        {
        }
        protected void InitDetailData(DataRow detailRow)
        {
        }
        public virtual void LoadDependencyData()
        {
        }
        protected virtual bool ValidateAll()
        {
            if (CurrentRow == null)
            {
                KPMessageBox.Show("CurrentRow Is null", KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
                return false;
            }
            if (!Validate())
                return false;
            if (!ValidateChildren(ValidationConstraints.None))
                return false;
            String[] arrMess = kP_BindingController.ValidateRequirement();
            if (arrMess.Length > 0)
            {
                KPMessageBox.Show(String.Join("\n", arrMess), KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Warning);
                return false;
            }
            if (CurrentRow.GetChildRows(Business.RelationName).Length == 0)
            {
                KPMessageBox.Show("Chi tiết phiếu không có!", KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Warning);
                return false;
            }
            return true;
        }
        private void bindingSource1_CurrentChanged(object sender, EventArgs e)
        {

        }

        private void kpucSaveItem_KPCloseClick(object sender, EventArgs e)
        {
            Close();
        }
        
        private void kpucSaveItem_KPSaveAndCloseClick(object sender, EventArgs e)
        {
            try
            {
                EndEdit();
                /*
                 * C1:
                 * Nếu là insert thi cứ DataRow.GetChildrenRow() là đủ
                 * Nếu là update thì DataRow.GetChildRow() để lấy row hiện tại rồi Merge với
                 *  DataRow.GetChildrenRow(RowVersion.Original)  để lấy row ban đầu 
                 *  --> Tập row đã xóa, row thay đổi.(Dùng cách này có khi hơn?)
                 *  
                 * C2:  DataSet dsChanged = CurrentRow.Table.DataSet.GetChanges();
                 * Cách này lượng dữ liệu đẩy qua tier 2 nhỏ hơn.
                 */
                DataRow[] childRow = ChildRows;
                CustomWriteData(CurrentRow, childRow);
                if (ValidateAll())
                {
                    if (FormState == FormState.Insert)
                    {
                        Business.Insert(CurrentRow, childRow);
                    }
                    if (FormState == FormState.Update)
                    {
                        Business.Update(CurrentRow, childRow);
                    }
                    FormState = FormState.Unspecified;
                    CurrentRow.Table.DataSet.AcceptChanges();
                    DialogResult = DialogResult.OK;
                }

            }
            catch (Exception ex)
            {
                KPMessageBox.Show( ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
        }

        private void kpucSaveItem_KPSaveAndNewClick(object sender, EventArgs e)
        {

            try
            {
                EndEdit();
                /*
                 * C1:
                 * Nếu là insert thi cứ DataRow.GetChildrenRow() là đủ
                 * Nếu là update thì DataRow.GetChildRow() để lấy row hiện tại rồi Merge với
                 *  DataRow.GetChildrenRow(RowVersion.Original)  để lấy row ban đầu 
                 *  --> Tập row đã xóa, row thay đổi.(Dùng cách này có khi hơn?)
                 *  
                 * C2:  DataSet dsChanged = CurrentRow.Table.DataSet.GetChanges();
                 * Cách này lượng dữ liệu đẩy qua tier 2 nhỏ hơn.
                 */
                DataRow[] childRow = ChildRows;
                CustomWriteData(CurrentRow, childRow);
                if (ValidateAll())
                {
                    if (FormState == FormState.Insert)
                    {
                        Business.Insert(CurrentRow, childRow);
                    }
                    if (FormState == FormState.Update)
                    {
                        Business.Update(CurrentRow, childRow);
                    }
                    FormState = FormState.Unspecified;
                    CurrentRow.Table.DataSet.AcceptChanges();
                    AddNew(ParentBinding);
                }

            }
            catch (Exception ex)
            {
                KPMessageBox.Show(ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
        }

        #region IContainerDataSource Members

        public virtual object GetSource(int index)
        {
            if (index == 1)
                return DetailBindingSource;
            return MasterBindingSource;
        }

        #endregion
    }
}
